using System;
using System.ComponentModel;
using System.Reflection;
using Mistral.Utils;
using Spring.Core.TypeConversion;
using Spring.Core.TypeResolution;

namespace Mistral.Configuration
{
	public class Registrator
	{
		public static void RegisterTypeAliasesByAttribute( Assembly assembly )
		{
			Type[] typesToRegister = ReflectionUtils.GetTypesFromAssembly( assembly,
			                                                               type => ReflectionUtils.HasAttribute( type, typeof ( RegisterAliasAttribute ) ) );
			Array.ForEach( typesToRegister,
			               type => TypeRegistry.RegisterType( ReflectionUtils.GetAttribute<RegisterAliasAttribute>(type).Alias, type ) );
		}

		public static void RegisterTypeAliasesByAttribute( )
		{
			Type[] typesToRegister = ReflectionUtils.GetTypesFromDomain( AppDomain.CurrentDomain,
			                                                             type => ReflectionUtils.HasAttribute( type, typeof ( RegisterAliasAttribute ) ) );
			Array.ForEach( typesToRegister,
			               type => TypeRegistry.RegisterType( ReflectionUtils.GetAttribute<RegisterAliasAttribute>(type).Alias, type ) );
		}

		public static void RegisterTypeConvertersByAttribute( )
		{
			Type[] typesToRegister = ReflectionUtils.GetTypesFromDomain( AppDomain.CurrentDomain,
			                                                             type => ReflectionUtils.HasAttribute( type, typeof ( RegisterConverterAttribute ) ) &&
			                                                                     typeof(TypeConverter).IsAssignableFrom( type ) );
			Array.ForEach( typesToRegister,
			               type => TypeConverterRegistry.RegisterConverter(
			                       	ReflectionUtils.GetAttribute<RegisterConverterAttribute>(type).Type,
			                       	(TypeConverter)Activator.CreateInstance(type) ) );
		}			
	}
}